// src/contexts/AuthContext.jsx - 用户认证上下文
import React, { createContext, useContext, useState, useEffect } from 'react'

const AuthContext = createContext()

// 使用认证上下文的Hook
export const useAuth = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

// 认证Provider组件
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)
  const [token, setToken] = useState(null)

  // 初始化时检查本地存储的用户信息
  useEffect(() => {
    const storedUser = localStorage.getItem('user')
    const storedToken = localStorage.getItem('token')
    
    if (storedUser && storedToken) {
      try {
        setUser(JSON.parse(storedUser))
        setToken(storedToken)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        // 清除无效数据
        localStorage.removeItem('user')
        localStorage.removeItem('token')
      }
    }
    setLoading(false)
  }, [])

  // 登录函数
  const login = async (email, password) => {
    try {
      // 模拟API调用
      const response = await mockLoginAPI(email, password)
      
      if (response.success) {
        const userData = {
          id: response.user.id,
          username: response.user.username,
          email: response.user.email,
          major: response.user.major,
          graduationYear: response.user.graduationYear,
          avatar: response.user.avatar
        }
        
        setUser(userData)
        setToken(response.token)
        
        // 保存到本地存储
        localStorage.setItem('user', JSON.stringify(userData))
        localStorage.setItem('token', response.token)
        
        return { success: true, user: userData }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请重试' }
    }
  }

  // 注册函数
  const register = async (userData) => {
    try {
      // 模拟API调用
      const response = await mockRegisterAPI(userData)
      
      if (response.success) {
        const newUser = {
          id: response.user.id,
          username: response.user.username,
          email: response.user.email,
          major: response.user.major,
          graduationYear: response.user.graduationYear,
          avatar: response.user.avatar
        }
        
        setUser(newUser)
        setToken(response.token)
        
        // 保存到本地存储
        localStorage.setItem('user', JSON.stringify(newUser))
        localStorage.setItem('token', response.token)
        
        return { success: true, user: newUser }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, message: '注册失败，请重试' }
    }
  }

  // 登出函数
  const logout = () => {
    setUser(null)
    setToken(null)
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }

  // 检查是否已登录
  const isAuthenticated = () => {
    return user !== null && token !== null
  }

  // 获取认证头
  const getAuthHeader = () => {
    return token ? { Authorization: `Bearer ${token}` } : {}
  }

  const value = {
    user,
    token,
    loading,
    login,
    register,
    logout,
    isAuthenticated,
    getAuthHeader
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

// 模拟登录API
const mockLoginAPI = async (email, password) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟用户数据库
  const mockUsers = [
    {
      id: 1,
      username: 'testuser',
      email: 'test@example.com',
      password: '12345678',
      major: '计算机科学与技术',
      graduationYear: 2024,
      avatar: '👨‍💻'
    },
    {
      id: 2,
      username: 'admin',
      email: 'admin@example.com',
      password: 'admin123',
      major: '软件工程',
      graduationYear: 2023,
      avatar: '👩‍💼'
    }
  ]
  
  const user = mockUsers.find(u => u.email === email && u.password === password)
  
  if (user) {
    return {
      success: true,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        major: user.major,
        graduationYear: user.graduationYear,
        avatar: user.avatar
      },
      token: `mock_token_${user.id}_${Date.now()}`
    }
  } else {
    return {
      success: false,
      message: '邮箱或密码错误'
    }
  }
}

// 模拟注册API
const mockRegisterAPI = async (userData) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1200))
  
  // 模拟邮箱重复检查
  const existingEmails = ['test@example.com', 'admin@example.com']
  
  if (existingEmails.includes(userData.email)) {
    return {
      success: false,
      message: '该邮箱已被注册'
    }
  }
  
  // 模拟成功注册
  const newUser = {
    id: Date.now(), // 简单的ID生成
    username: userData.username,
    email: userData.email,
    major: userData.major,
    graduationYear: userData.graduationYear,
    avatar: '👤' // 默认头像
  }
  
  return {
    success: true,
    user: newUser,
    token: `mock_token_${newUser.id}_${Date.now()}`
  }
}

export default AuthContext